package com.hw.shortlink.project.dao.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.hw.shortlink.project.dao.entity.LinkLocaleStats;
import com.hw.shortlink.project.dto.req.ShortLinkGroupStatsReqDto;
import com.hw.shortlink.project.dto.req.ShortLinkStatsReqDto;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface LinkLocaleStatsMapper  extends BaseMapper<LinkLocaleStats> {

    /**
     * 记录短链接地区访问记录
     * @param linkLocaleStats
     */
    @Insert("INSERT INTO tb_link_locale_stats (full_short_url, date, cnt, province, city, adcode, country, create_time, update_time, del_flag) " +
            "VALUES( #{reqDto.fullShortUrl},  #{reqDto.date}, #{reqDto.cnt}," +
            " #{reqDto.province}, #{reqDto.city}, #{reqDto.adcode}, #{reqDto.country}, NOW(), NOW(), 0) " +
            "ON DUPLICATE KEY UPDATE cnt = cnt +  #{reqDto.cnt}")
    void shortLinkLocaleStats(@Param("reqDto") LinkLocaleStats linkLocaleStats);


    /**
     * 查询某个短链接的地区统计信息
     * @param shortLinkStatsReqDto
     * @return
     */
    @Select("SELECT " +
            "    province , " +
            "    SUM(cnt) AS cnt " +
            "FROM " +
            "    tb_link_locale_stats " +
            "WHERE " +
            "    full_short_url = #{reqDto.fullShortUrl} " +
            "    AND date BETWEEN #{reqDto.startDate} and #{reqDto.endDate} " +
            "GROUP BY " +
            "    province")
    List<LinkLocaleStats> listLocaleStatsByShortLink(@Param("reqDto") ShortLinkStatsReqDto shortLinkStatsReqDto);

    //todo fix
    /**
     * 查询某个分组的地区统计信息
     * @param shortLinkGroupStatsReqDto
     * @return
     */
    @Select("SELECT " +
            "    province , " +
            "    SUM(cnt) AS cnt " +
            "FROM " +
            "    tb_link_locale_stats " +
            "WHERE " +
            "   gid = #{reqDto.gid} " +
            "    AND date BETWEEN #{reqDto.startDate} and #{reqDto.endDate} " +
            "GROUP BY " +
            "    full_short_url, gid,province")
    List<LinkLocaleStats> listLocaleStatsByGroup(@Param("reqDto") ShortLinkGroupStatsReqDto shortLinkGroupStatsReqDto);
}
